package com.app.medicalcontrol.bean;


import android.content.Context;

import com.app.medicalcontrol.basis.BasisApp;
import com.app.medicalcontrol.basis.Constants;
import com.app.medicalcontrol.jpush.TagAliasOperatorHelper;
import com.app.medicalcontrol.login.LoginActivity;
import com.loopj.android.http.RequestParams;

import java.util.Date;

import my.FileUtils;
import my.LogUtil;
import my.MySharedPreferences;
import my.TimeUtils;
import my.http.HttpRestClient;
import my.http.MyHttpListener;


public class LoginBean extends BasisBean implements Cloneable {
    private static final long serialVersionUID = 1L;

    public static final int ERRO_CODE_DEVICE = -3001;


    public static final int LOGIN_TYPE_PERSON = 0;
    public static final int LOGIN_TYPE_FA = 1;

    public static final String FILE_CACHE = Constants.DIR_FILE
            + "login.data";
    private static LoginBean sLoginBean;

    private int store_id;
    private Token token;
    private long sys_time;
    private String clerkId_md5;
    private Ticket ticket;
    private String nick_name;
    private String headPic;
    public void setStore_id(int store_id) {
        this.store_id = store_id;
    }
    public int getStore_id() {
        return store_id;
    }

    public void setToken(Token token) {
        this.token = token;
    }
    public Token getToken() {
        return token;
    }

    public void setSys_time(long sys_time) {
        this.sys_time = sys_time;
    }
    public long getSys_time() {
        return sys_time;
    }

    public void setClerkId_md5(String clerkId_md5) {
        this.clerkId_md5 = clerkId_md5;
    }
    public String getClerkId_md5() {
        return clerkId_md5;
    }

    public void setTicket(Ticket ticket) {
        this.ticket = ticket;
    }
    public Ticket getTicket() {
        return ticket;
    }

    public void setNick_name(String nick_name) {
        this.nick_name = nick_name;
    }
    public String getNick_name() {
        return nick_name;
    }

    public void setHeadPic(String headPic) {
        this.headPic = headPic;
    }
    public String getHeadPic() {
        return headPic;
    }



    public LoginBean() {
        super();
        // sLoginBean = this;
    }

    public static boolean isLogin() {
		return getInstance() != null && !(sLoginBean.getStore_id()==0);
//        return getInstance() != null && getInstance().getUser() != null;
//        return false;
    }

    public static LoginBean getInstance() {
        if (sLoginBean == null)
            sLoginBean = getFromCache();
        return sLoginBean;
    }

    public static LoginBean getFromCache() {
        LoginBean data;
        data = (LoginBean) FileUtils.readObject(FILE_CACHE);
        if (data != null) {
            sLoginBean = data;
        }
        LogUtil.i("login---->getFromCache---" + (data == null));
        return data;
    }

    public void save() {
        sLoginBean = this;
        boolean c = FileUtils.cacheObject(FILE_CACHE, this);
        // FileSaveHandler.saveObject(FILE_CACHE, this);
        LogUtil.i("login---->save---" + FILE_CACHE);
    }

    private static void delete() {
        FileUtils.cacheObject(FILE_CACHE, null);
        // FileSaveHandler.removeObject(FILE_CACHE);
    }

	public static void logout() {
		delete();
		sLoginBean = null;
        TagAliasOperatorHelper.getInstance().cleanAlias();
	}

    public static void logout(Context mContext) {
        delete();
        sLoginBean = null;
        MySharedPreferences mSp = new MySharedPreferences(mContext);
        mSp.putIsLogined(false);
        mSp.putPassword("");
        mSp.putUser("");
        TagAliasOperatorHelper.getInstance().cleanAlias();
    }

    public static void logPast(Context mContext) {
        delete();
        sLoginBean = null;
        MySharedPreferences mSp = new MySharedPreferences(mContext);
        mSp.putIsLogined(false);
    }

    public Object clone() {
        try {
            return super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static int getStoreId() {
        if (isLogin()) return getInstance().getStore_id();
        return 0;
    }
    public static String getUserToken() {
        if (isLogin()) return getInstance().getToken().getValue();
        return "";
    }

    public String getJpushAlias() {
//        return getClerkId_md5();
        return "spad_"+getClerkId_md5();
    }

    public static class Token extends BasisBean{
    private long time_expire;
    private String value;
    public void setTime_expire(long time_expire) {
        this.time_expire = time_expire;
    }
    public long getTime_expire() {
        return time_expire;
    }

    public void setValue(String value) {
        this.value = value;
    }
    public String getValue() {
        return value;
    }

    public boolean isTokenPast(){
        return TimeUtils.DateCompare(time_expire*1000,new Date().getTime()) < 0;
    }
}

    public static class Ticket extends BasisBean{
        private long time_expire;
        private String value;
        public void setTime_expire(long time_expire) {
            this.time_expire = time_expire;
        }
        public long getTime_expire() {
            return time_expire;
        }

        public void setValue(String value) {
            this.value = value;
        }
        public String getValue() {
            return value;
        }
        public boolean isTicketPast(){
            return TimeUtils.DateCompare(time_expire*1000,new Date().getTime()) < 0;
        }
    }

    /**
     * 刷新token，成功情况在Token_Listener中
     *
     * @param listener
     */
    public static void refreshToken(final Token_Listener listener){
        refreshToken(listener,false);
    }

    /**
     * 刷新token，成功情况在Token_Listener中
     *
     * @param listener
     */
    public static void refreshToken(final Token_Listener listener, boolean isFoceReresh) {
        boolean a = LoginBean.isLogin();
        if (!LoginBean.isLogin()) {
            if (listener != null) {
                listener.onFailure();
                listener.onFinish();
            }
            return;
        }

        if(!isFoceReresh && !getInstance().getToken().isTokenPast() ){
            LogUtil.i("token未过期");
            listener.onSuccess();
            listener.onFinish();
            return;
        }

        if(  !isFoceReresh && getInstance().getTicket().isTicketPast()){
            LogUtil.i("Ticket已过期");
            LoginBean.logout();
            if (listener != null) {
                listener.onFailure();
                listener.onFinish();
            }
            LoginActivity.toLoadingAllClear(BasisApp.mContext);
            return;
        }

        RequestParams params = new RequestParams();
        params.put("cticket", LoginBean.getInstance().getTicket().getValue());
        HttpRestClient.post(Constants.URL_GET_TOKEN, params, new MyHttpListener() {
            @Override
            public void onSuccess(int httpWhat, Object result) {
                LogUtil.i("刷新token成功");
                LoginBean bean = (LoginBean) result;
                LoginBean loginBean = LoginBean.getInstance();
                loginBean.setToken(bean.getToken());
                loginBean.save();
                if (listener != null) {
                    listener.onSuccess();
                }
            }

            @Override
            public void onFailure(int httpWhat, Object result) {
//                super.onFailure(httpWhat, result);
                LoginBean.logout();
                if (listener != null) {
                    listener.onFailure();
                }
                LoginActivity.toLoadingAllClear(BasisApp.mContext);
            }

            @Override
            public boolean onHttpFailure(int httpWhat, Throwable arg3) {
//                return super.onHttpFailure(httpWhat, arg3);
                if (listener != null) {
                    listener.onSuccess();
                }
                return true;
            }

            @Override
            public void onFinish(int httpWhat) {
                if (listener != null) {
                    listener.onFinish();
                }
            }
        }, 0, LoginBean.class);
    }

    public interface Token_Listener {
        void onSuccess();
        void onFailure();
        void onFinish();
    }

    public static void RefreshTokenOnly(){
        if(!isLogin())return;
        refreshToken(new Token_Listener() {
            @Override
            public void onSuccess() {

            }

            @Override
            public void onFailure() {

            }

            @Override
            public void onFinish() {

            }
        },true);
    }


}
